package cn.dancepeak.role.service.impl;

import cn.dancepeak.exception.BusinessException;
import cn.dancepeak.role.domain.Role;
import cn.dancepeak.role.mapper.RoleMapper;
import cn.dancepeak.role.query.RoleQuery;
import cn.dancepeak.role.service.IRoleServiceImpl;
import cn.dancepeak.vo.ArticleTypeTree;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class RoleServiceImplImpl implements IRoleServiceImpl {
    @Autowired
    private RoleMapper roleMapper;
    @Override
    @Transactional
    public void add(Role role) {
        //判断是否注册过
        Role role1 = roleMapper.selectByRoleName(role.getName());
        if(ObjectUtil.isNotNull(role1)){
            throw new BusinessException("账号已被注册");
        }
        //保存角色返回自增id
        roleMapper.insert(role);
        //保存角色信息  需要返回中间表信息
        roleMapper.saveRoleMenu(role);
        roleMapper.saveRolePermission(role);
    }

    @Override
    @Transactional
    public void update(Role role) {
        //用户名不能修改   禁用  在前端写
        roleMapper.updateById(role);
        //修改角色信息要先删脏数据在添加
        roleMapper.deleteRolePermissionById(role.getId());
        roleMapper.deleteRoleMenuById(role.getId());
        roleMapper.saveRoleMenu(role);
        roleMapper.saveRolePermission(role);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        roleMapper.deleteById(id);
        //删除角色同样吧中间表的脏数据删除
        roleMapper.deleteRolePermissionById(id);
        roleMapper.deleteRoleMenuById(id);
    }

    @Override
    @Transactional
    public void deleteByList(List<Long> ids) {
        roleMapper.deleteByList(ids);
        //删除角色同样吧中间表的脏数据删除
        for (Long id : ids) {
            roleMapper.deleteRolePermissionById(id);
            roleMapper.deleteRoleMenuById(id);
        }
    }

    @Override
    public Role getById(Long id) {
        return roleMapper.selectById(id);
    }

    @Override
    public PageInfo<Role> page(RoleQuery roleQuery) {
        // 1.下面这句代码表示开启分页，会将紧挨着这句代码的下一次数据库执行进行分页，切记一定要放在要分页的SQL语句前面执行
        // 2.执行SQL语句带条件查询，SQL语句不需要进行分页
        PageHelper.startPage(roleQuery.getCurrentPage(), roleQuery.getPageSize());
        List<Role> role = roleMapper.list(roleQuery);
        // 3.将查询结果转换为PageInfo对象，PageInfo对象中有前端分页所需要的各种参数
        PageInfo<Role> pageInfo = new PageInfo<>(role);
        // 4.响应总条数和分页信息
        return pageInfo;
    }

    @Override
    public List<Role> getAll() {
        return roleMapper.getAll();
    }


}